<template>
  <div>
    <div>
      <div>
        <span
          v-if="imgpath=='images/id.jpg'"
          :style="{backgroundImage:'url(' + imgpath + ')',backgroundSize:(imgpath=='images/id.jpg'?'30%':'100%')}"
          class="upload2"

        >
          <input
            v-if="imgpath=='images/id.jpg'"
            id="id"
            ref="inputer"
            class="change"
            type="file"
            capture="camera"
            @change="handleFile"
          >
          <i
            v-if="imgpath=='images/id.jpg'"
            class="el-icon-loading" />
        </span>
        <div>
          <span
            v-if="imgpath!='images/id.jpg'"
            :style="{backgroundImage:'url(' + imgpath + ')',backgroundSize:(imgpath=='images/id.jpg'?'30%':'100%')}"
            class="upload2"
            @click="isshow=true"
          />
          <b
            v-if="imgpath!='images/id.jpg'"
            style="font-size:30px;"
            @click="deletes">×</b>
        </div>
      </div>

      <!-- <ul
        v-show="imgpath!==''&&imgpath!==undefined"
        id="content">
        <li
          v-if="wordfiletype == 'jpg' ||wordfiletype == 'png'"
          @click="showPic">
          <img
            :src="imgpath"
            alt
            style="height:96px;margin:10px 0">
        </li>
      </ul>-->
      <div
        v-show="isshow"
        class="picContent"
        @click="hidepic">
        <img
          :src="imgpath"
          alt
          style="width: 100%;height:auto;position:relative;display:block;margin:0 auto;"
        >
      </div>
    </div>
  </div>
</template>
<style>
</style>

<script>
import SparkMD5 from 'spark-md5'
import OSS from 'ali-oss'
import { log } from 'util'
import Exif from 'exif-js'

const baseUrl = 'http://assets.eke88.com:5000' //http://hg.eke88.com
let chunkSize = 1 * 1024 * 1024

let file = null
let fileSize = 0
let chunks = 5
let blobSlice
let currentChunk = 0
let fileReader

export default {
  props: {
    // eslint-disable-next-line vue/require-default-prop
    tn: {
      type: String
    },
    // eslint-disable-next-line vue/require-default-prop
    imagefile: {
      type: Object
    },
    // eslint-disable-next-line vue/require-default-prop
    localfiletype: {
      type: Number
    },
    imgwidth: {
      type: Number
    },
    // eslint-disable-next-line vue/require-default-prop
    isupload: {
      type: String
    }
  },

  data() {
    return {
      uploadimg: 'images/id.jpg',
      shouPic: true,
      debug: false,
      wordfilename: '',
      wordfiletype: '',
      ts: this.newStore(),
      aa: this.newStore(),
      list: [],
      imgpath: 'images/id.jpg',
      isshow: false,
      localFilename: '查看'
    }
  },
  // watch: {
  //   imagefile() {
  //     alert('111')
  //     if (this.imagefile) {
  //       this.imgpath = this.imagefile[this.tn]
  //       if (
  //         this.imgpath &&
  //         this.imgpath.length > 0 &&
  //         this.imgpath.split('.').length > 0
  //       ) {
  //         this.wordfiletype = this.imgpath.split('.')[
  //           this.imgpath.split('.').length - 1
  //         ]
  //       }
  //       console.log(this.imgpath)
  //     } else {
  //       this.imgpath = ''
  //     }
  //   }
  // },
  methods: {
    dataURLtoBlob(dataurl) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new Blob([u8arr], { type: mime })
    },
    Base64ToBlob(base64) {
      var base64Arr = base64.split(',')
      var imgtype = ''
      var base64String = ''
      if (base64Arr.length > 1) {
        //如果是图片base64，去掉头信息
        base64String = base64Arr[1]
        imgtype = base64Arr[0].substring(
          base64Arr[0].indexOf(':') + 1,
          base64Arr[0].indexOf(';')
        )
      }
      // 将base64解码
      var bytes = atob(base64String)
      //var bytes = base64;
      var bytesCode = new ArrayBuffer(bytes.length)
      // 转换为类型化数组
      var byteArray = new Uint8Array(bytesCode)

      // 将base64转换为ascii码
      for (var i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i)
      }

      // 生成Blob对象（文件对象）
      return new Blob([bytesCode], { type: imgtype })
    },
    doput(data) {
      let client = new OSS({
        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用STS方式来进行API访问
        accessKeyId: 'LTAI4Fzq16DqFTFnZwZsNmKP',
        accessKeySecret: 'OlovgPm6eXjaDzaUQlkjiwyNrUvxoc',
        endpoint: 'http://oss-cn-beijing.aliyuncs.com/' + fname,
        bucket: 'hgupload'
      })
      let imgdata = this.Base64ToBlob(data)
      let fname = Math.random()
        .toString(36)
        .substr(2)
      client
        .put(fname, imgdata)
        .then(r1 => {
          // console.log('put success: %j', r1.url)
          this.$emit('update:imagefile', '')
          this.imgpath = r1.url
          setTimeout(() => {
            console.log(r1, '000000')

            this.$emit('update:imagefile', r1)
          }, 50)

          // this.changePic(r1.url)
          this.$root.loading = false
          return client.get(fname)
        })
        .then(function(r2) {
          console.log('get success: %j', r2)
        })
        .catch(function(err) {
          console.error('error: %j', err)
        })
    },

    handleFile(e) {
      this.$root.loading = true
      let $target = e.target || e.srcElement
      let file = $target.files[0]
      //console.log((file.size / 1024).toFixed(2) + 'KB')
      let Orientation
      //去获取拍照时的信息，解决拍出来的照片旋转问题
      Exif.getData(file, function() {
        Orientation = Exif.getTag(this, 'Orientation')
        //console.log(Exif.getAllTags(this), '12222222')
      })
      console.log(Orientation, '111111111')

      var reader = new FileReader()
      reader.readAsDataURL(file)
      new Promise((resolve, reject) => {
        reader.onload = e => {
          var image = document.createElement('img')
          image.src = e.target.result
          new Promise((resolve, reject) => {
            image.onload = () => {
              var data = '',
                canvas = document.createElement('canvas'),
                context = canvas.getContext('2d'),
                imageWidth = image.width,
                imageHeight = image.height

              //压缩图片
              if (imageWidth > 1000 || imageHeight > 1000) {
                //等比例压缩，不失真，不裁剪
                if (imageWidth > imageHeight) {
                  imageWidth = 1000
                  imageHeight = (imageWidth * imageHeight) / image.width
                } else {
                  imageHeight = 1000
                  imageWidth = (imageHeight * imageWidth) / image.height
                }
              }

              //旋转到正常角度,位置偏移
              var angle = 0
              var x = 0,
                y = 0,
                w = imageWidth,
                h = imageHeight //canvas画布
              // 定义画布的大小
              canvas.width = imageWidth
              canvas.height = imageHeight
              context.drawImage(image, x, y, imageWidth, imageHeight)

              /*
                            Orientation:
                            3:ios手机底部在左边，拍出来的横图是倒置的，需要旋转180度
                            6:ios手机底部朝下，拍出来的照片是头在右边，需要逆时针旋转90度
                        */
              //this.rotateImg(image, 'half', canvas)
              if (Orientation) {
                switch (Orientation) {
                  case 3:
                    this.rotateImg(image, 'half', canvas) //转两次
                    break
                  case 6:
                    this.rotateImg(image, 'left', canvas)
                    break
                  case 8:
                    this.rotateImg(image, 'right', canvas)
                    break

                  default:
                    break
                }
              }
              // context.rotate(angle);
              // 画图
              // context.drawImage(this, x, y,imageWidth,imageHeight);
              data = canvas.toDataURL('image/jpeg') //转成bae64编码
              // console.log(data)

              resolve(data)
            }
            image.onerror = e => {
              reject(e)
            }
          }).then(data => {
            this.doput(data)
          })
        }
      })

      // object表示上传到OSS的名字，可自己定义
      // file浏览器中需要上传的文件，支持HTML5 file 和 Blob类型
    },

    changePic(pic) {
      //console.log('changepic', this.tn)
      this.imgpath = pic

      this.imagefile[this.tn] = pic
      //console.log(this.imagefile)

      if (
        this.imgpath &&
        this.imgpath.length > 0 &&
        this.imgpath.split('.').length > 0
      ) {
        this.wordfiletype = this.imgpath.split('.')[
          this.imgpath.split('.').length - 1
        ]
      }
      // alert(this.tn);
      // this.$emit('getTestinput', this.imgpath, this.tn);
    },
    showPic() {
      this.isshow = true
    },
    hidepic() {
      this.isshow = false
    },

    //对图片旋转处理 added by lzk
    rotateImg(img, direction, canvas) {
      //alert(img);
      //最小与最大旋转方向，图片旋转4次后回到原方向
      var min_step = 0
      var max_step = 3
      //var img = document.getElementById(pid);
      if (img == null) return
      //img的高度和宽度不能在img元素隐藏后获取，否则会出错
      var height = img.height
      var width = img.width
      //var step = img.getAttribute('step');
      var step = 2
      if (step == null) {
        step = min_step
      }
      if (direction == 'right') {
        step++
        //旋转到原位置，即超过最大值
        step > max_step && (step = min_step)
      } else {
        step--
        step < min_step && (step = max_step)
      }
      //img.setAttribute('step', step);
      /*var canvas = document.getElementById('pic_' + pid);
        if (canvas == null) {
            img.style.display = 'none';
            canvas = document.createElement('canvas');
            canvas.setAttribute('id', 'pic_' + pid);
            img.parentNode.appendChild(canvas);
        }  */
      //旋转角度以弧度值为参数
      var degree = (step * 90 * Math.PI) / 180
      var ctx = canvas.getContext('2d')
      switch (step) {
        case 0:
          canvas.width = width
          canvas.height = height
          ctx.drawImage(img, 0, 0)
          break
        case 1:
          canvas.width = height
          canvas.height = width
          ctx.rotate(degree)
          ctx.drawImage(img, 0, -height)
          break
        case 2:
          canvas.width = width
          canvas.height = height
          ctx.rotate(degree)
          ctx.drawImage(img, -width, -height)
          break
        case 3:
          canvas.width = height
          canvas.height = width
          ctx.rotate(degree)
          ctx.drawImage(img, -width, 0)
          break
      }
    },
    verificationPicFile(pfile) {
      const fileTypes = ['.jpg', '.png']
      const filePath = pfile.value
      // 当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
      if (filePath) {
        let isNext = false
        const fileEnd = filePath.substring(filePath.indexOf('.'))
        for (let i = 0; i < fileTypes.length; i += 1) {
          if (fileTypes[i] === fileEnd) {
            isNext = true
            break
          }
        }
        if (!isNext) {
          this.$messagebox('提示', '不接受此文件类型')
          this.$messagebox('提示2', '不接受此文件类型')
          pfile.value = ''
          return false
        }
      } else {
        return false
      }
      return true
    },
    deletes() {
      this.imgpath = 'images/id.jpg'
      this.imagefile = {}
      console.log()
    }
  }
}
</script>
<style scoped>
.info-wrapper .info-content .upload-btn[data-v-0cbaa4e1] {
  background: #f1f1f1;
}

.picContent {
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  margin: 0;
  margin: 0 auto;
  z-index: 5000;
  width: 100%;
  overflow: auto;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload1 {
  /* padding: 10px 20px; */
  /* line-height: 30px; */
  /* position: relative; */
  /* background: #339999; */
  border-radius: 3px;
  text-decoration: none;
  color: #fff;
  font-size: 14px;
  background-repeat: no-repeat;
  background-size: 40%;
  /* height: 100px; */
  display: block;
  /* width: 337px; */
  margin-left: 10px;
}
.upload2 {
  /* background-size:100% !important; */
  /* padding: 10px 20px; */
  /* line-height: 30px; */
  /* position: relative; */
  /* background: #339999; */
  height: 35px;
  border-radius: 3px;
  text-decoration: none;
  color: #fff;
  font-size: 14px;
  background-repeat: no-repeat;
  background-size: 40%;
  /* height: 100px; */
  display: block;
  /* width: 337px; */
  /* margin-left: 10px; */
}
.upload21 {
  /* padding: 10px 20px; */
  /* line-height: 30px; */
  /* position: relative; */
  /* background: #339999; */
  height: 95px;
  border-radius: 3px;
  text-decoration: none;
  color: #fff;
  font-size: 14px;
  background-repeat: no-repeat;
  background-size: 35%;
  /* height: 100px; */
  display: block;
  /* width: 337px; */
  margin-left: 10px;
}
.change {
  opacity: 0;
  width: 60px;
  height: 40px;
}
ul {
  margin-top: 2px;
  font-size: 14px;
  padding: 0 10px;
}
</style>
